//
//  LZMyCouponsViewController.m
//  laziz_Consumer
//
//  Created by ZhaoDongBo on 2016/10/31.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZMyCouponsViewController.h"

#import "LZMyCouponsTableView.h"
#import "HTHorizontalSelectionList.h"

#import "UIViewController+NavigationItemSetting.h"
#import "UITableView+LZTableView.h"

#import "Masonry.h"

#import "LZMyCouponsListPresenter.h"
#import "MJRefresh.h"
#import "LZMyRestaurantCoupons.h"
#import "LZMyCouponsModel.h"
#import "LZGrabCouponDetailViewController.h"
#import "LZFightGroupDetailViewController.h"
#import "LZGroupDetailViewController.h"

#import "LZNoDataPublicView.h"

@interface LZMyCouponsNumModel ()

@property (nonatomic, assign) int unUsedNum;        // 未使用的数
@property (nonatomic, assign) int usedNum;          // 已使用的数
@property (nonatomic, assign) int expiredNum;       // 已过期的数
@property (nonatomic, assign) int processNum;       // 进行中的数

@end

@implementation LZMyCouponsNumModel



@end

@interface LZMyCouponsViewController () <HTHorizontalSelectionListDelegate, HTHorizontalSelectionListDataSource>

@property (nonatomic, strong) LZMyCouponsTableView * tableView;
@property (nonatomic, strong) HTHorizontalSelectionList * headerListView;
@property (nonatomic, strong) NSMutableArray *carMakes;
@property (nonatomic, strong) LZMyCouponsNumModel *numModel;

@property (nonatomic, strong) NSMutableArray * dataArrays;

@property (nonatomic, assign) NSInteger pageNum;
@property (nonatomic, assign) NSInteger pageLimit;
@property (nonatomic, assign) NSInteger currentIndex;

@end

@implementation LZMyCouponsViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configViewData];
    
    [self setup];
    
    [self addAutoLayout];

    [self.tableView.mj_footer beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)configViewData {
    self.umLogPageViewName = @"我的优惠劵页面";
    
    self.view.backgroundColor = UIColorFromRGB(0xffffff, 1);
    self.pageNum = 1;
    self.pageLimit = 50;
    self.currentIndex = 0;
    self.dataArrays = [NSMutableArray array];
    
    self.numModel = [[LZMyCouponsNumModel alloc] init];
    self.numModel.unUsedNum = 0;
    self.numModel.usedNum = 0;
    self.numModel.expiredNum = 0;
    self.numModel.processNum = 0;
    
    self.carMakes = [@[
                      [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_notused", nil),
                       [NSString stringWithFormat:@"%d",self.numModel.unUsedNum]],
                      [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_used", nil),
                       [NSString stringWithFormat:@"%d",self.numModel.usedNum]],
                      [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_expired", nil),
                       [NSString stringWithFormat:@"%d",self.numModel.expiredNum]],
                      [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_pending", nil),
                       [NSString stringWithFormat:@"%d",self.numModel.processNum]]] mutableCopy];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(checkOutNotificationAction:)
                                                 name:@"checkOutNotification"
                                               object:nil];
    
}

- (void)setup {
    
    WS(weakSelf);

    [self.view addSubview:self.headerListView];
    [self.view addSubview:self.tableView];

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(upLoadMoreVideoListData)];
    [self.tableView configFooterRefreshText];
    
    self.tableView.didSelectRowBlock = ^(NSIndexPath * indexPath) {
        
        __block LZMyRestaurantCoupons * restModel = weakSelf.dataArrays[indexPath.section];
        if (restModel) {
            __block LZMyCouponsModel * coupModel = restModel.couponDTO[indexPath.row];
            if (coupModel) {
                if (weakSelf.currentIndex == 3) {
                    //团购详情 进行中
                    LZGroupDetailViewController *vc = [[LZGroupDetailViewController alloc] init];
                    vc.grouponId = [coupModel.groupId copy];
                    vc.disCountNo = [coupModel.disCountNo copy];
                    vc.indexPath = indexPath;
                    vc.isUserCenter = YES;
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                    
                    vc.cancelOrQuitGrouponBlock = ^(NSIndexPath *lzIndexPath) {
                        // 先移除DTO
                        [restModel.couponDTO removeObject:coupModel];
                        if (restModel.couponDTO.count == 0) {
                            // 如果餐厅里边的DTO数组是空的，则移除餐厅
                            [weakSelf.dataArrays removeObject:restModel];
                        }
                        [weakSelf.tableView reloadData];
                        
                        // 改变上边对应的数
                        if (weakSelf.numModel.processNum > 0) {
                            weakSelf.numModel.processNum --;
                            [weakSelf.carMakes replaceObjectAtIndex:3 withObject:[NSString stringWithFormat:LZLocalizedString(@"mine_coupons_pending", nil),
                                                                                  [NSString stringWithFormat:@"%d",weakSelf.numModel.processNum]]];
                            [weakSelf.headerListView reloadData];
                        }
                    };
                }
                else {
                    //优惠劵详情 or groupon 其他状态(未使用, 已使用, 过期)
                    CouponState couponStateTemp = kCoupon_default;
                    switch (weakSelf.currentIndex) {
                        case 0:
                            couponStateTemp = kCoupon_notUsed;
                            break;
                        case 1:
                            couponStateTemp = kCoupon_used;
                            break;
                        case 2:
                            couponStateTemp = kCoupon_expired;
                            break;
                            
                        default:
                            break;
                    }
                    
                    if ([coupModel.promotionType isEqualToString:@"1"]) {//优惠券
                        LZGrabCouponDetailViewController *vc = [[LZGrabCouponDetailViewController alloc] init];
                        vc.couponState = couponStateTemp;
                        vc.videoID = coupModel.promotionId;
                        vc.disCountNo = [coupModel.disCountNo copy];
                        vc.disCountMoney = [coupModel.couponsMoney copy];
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                        
                    }else if ([coupModel.promotionType isEqualToString:@"2"]){//团购
                        LZFightGroupDetailViewController *vc = [[LZFightGroupDetailViewController alloc] init];
                        vc.videoID = coupModel.promotionId;
                        vc.couponState = couponStateTemp;
                        vc.disCountNo = [coupModel.disCountNo copy];
                        vc.disCountMoney = [coupModel.couponsMoney copy];
                        [weakSelf.navigationController pushViewController:vc animated:YES];
                    }
                    
                }
            }
        }
    };
}

- (void)addAutoLayout {
    
    WS(weakSelf);
    
    [self.headerListView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.height.mas_equalTo(52);
    }];
    
    [self.tableView makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(weakSelf.headerListView.mas_bottom);
        make.leading.mas_equalTo(0);
        make.trailing.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
    }];
}

#pragma mark - event

- (void)checkOutNotificationAction:(NSNotification *)notification {
    DLog(@"%@",notification);
    if (self.currentIndex != 0) {
        return;
    }
    
    NSDictionary *dic = notification.object;
    
    NSString *sellerId = dic[@"sellerId"];
    NSString *promotionId = dic[@"promotionId"];
    NSString *discountId = dic[@"discountId"];
    
    LZMyRestaurantCoupons * restModel = nil;
    
    // 通过 sellerId 找对应的餐厅
    if (sellerId.length>0) {
        NSArray *result_restaurant = [self.dataArrays filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.sellerId = %@",sellerId]];
        if (result_restaurant.count == 0) {
            return;
        }
        
        restModel = result_restaurant[0];
        
        if (discountId.length>0) {
            // 通过 discountId 找 couponDTO （这个是最准确的，但是第一版服务器没有这个字段，所以下边 else 里的逻辑是为了适配服务器）
            NSArray *result_couponDTO = [restModel.couponDTO filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.disCountNo = %@",discountId]];
            if (result_couponDTO.count == 0) {
                if (restModel.couponDTO.count == 0) {
                    // 如果餐厅里边的DTO数组是空的，则移除餐厅
                    [self.dataArrays removeObject:restModel];
                    [self.tableView reloadData];
                }
                return;
            }
            else {
                LZMyCouponsModel * coupModel = result_couponDTO[0];
                // 先移除DTO
                [restModel.couponDTO removeObject:coupModel];
                if (restModel.couponDTO.count == 0) {
                    // 如果餐厅里边的DTO数组是空的，则移除餐厅
                    [self.dataArrays removeObject:restModel];
                }
                [self.tableView reloadData];
                
                // 改变上边对应的数
                if (self.numModel.unUsedNum > 0) {
                    // 未使用的数  减1
                    self.numModel.unUsedNum --;
                    [self.carMakes replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:LZLocalizedString(@"mine_coupons_notused", nil),
                                                                      [NSString stringWithFormat:@"%d",self.numModel.unUsedNum]]];
                    
                    // 已使用的数  加1
                    self.numModel.usedNum ++;
                    [self.carMakes replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:LZLocalizedString(@"mine_coupons_used", nil),
                                                                      [NSString stringWithFormat:@"%d",self.numModel.usedNum]]];
                    
                    [self.headerListView reloadData];
                }
            }

        }
        else {
            // 通过 promotionId 找 couponDTO
            if (promotionId.length>0) {
                
                NSArray *result_couponDTO = [restModel.couponDTO filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.promotionId = %@",promotionId]];
                if (result_couponDTO.count == 0) {
                    if (restModel.couponDTO.count == 0) {
                        // 如果餐厅里边的DTO数组是空的，则移除餐厅
                        [self.dataArrays removeObject:restModel];
                        [self.tableView reloadData];
                    }
                    return;
                }
                else if (result_couponDTO.count == 1) {
                    // 如果该餐厅只有一个优惠
                    
                    // 先移除DTO
                    [restModel.couponDTO removeAllObjects];
                    [self.dataArrays removeObject:restModel];
                    [self.tableView reloadData];
                    
                    // 改变上边对应的数
                    if (self.numModel.unUsedNum > 0) {
                        // 未使用的数  减1
                        self.numModel.unUsedNum --;
                        [self.carMakes replaceObjectAtIndex:0 withObject:[NSString stringWithFormat:LZLocalizedString(@"mine_coupons_notused", nil),
                                                                          [NSString stringWithFormat:@"%d",self.numModel.unUsedNum]]];
                        // 已使用的数  加1
                        self.numModel.usedNum ++;
                        [self.carMakes replaceObjectAtIndex:1 withObject:[NSString stringWithFormat:LZLocalizedString(@"mine_coupons_used", nil),
                                                                          [NSString stringWithFormat:@"%d",self.numModel.usedNum]]];
                        
                        [self.headerListView reloadData];
                    }
                }
                else {
                    /* 为了适配后台，暂不处理 */
                }
            }
        }
    }
}
- (void)upLoadMoreVideoListData
{
    [self requestData:self.currentIndex+1];
}

- (void)requestData:(NSInteger)index {
    
    WS(weakSelf);
    [LZMyCouponsListPresenter getMyCouponsList:index
                                       pageNum:self.pageNum
                                     pageLimit:self.pageLimit
                                 resultSuccess:^(NSMutableArray * data, int unUsedNum, int usedNum, int expiredNum, int processNum, int totlePageTemp) {
                                     
                                     weakSelf.numModel.unUsedNum = unUsedNum;
                                     weakSelf.numModel.usedNum = usedNum;
                                     weakSelf.numModel.expiredNum = expiredNum;
                                     weakSelf.numModel.processNum = processNum;
                                     
                                     weakSelf.carMakes = [@[
                                                           [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_notused", nil),
                                                            [NSString stringWithFormat:@"%d",weakSelf.numModel.unUsedNum]],
                                                           [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_used", nil),
                                                            [NSString stringWithFormat:@"%d",weakSelf.numModel.usedNum]],
                                                           [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_expired", nil),
                                                            [NSString stringWithFormat:@"%d",weakSelf.numModel.expiredNum]],
                                                           [NSString stringWithFormat:LZLocalizedString(@"mine_coupons_pending", nil),
                                                            [NSString stringWithFormat:@"%d",weakSelf.numModel.processNum]]] mutableCopy];
                                     
                                     [weakSelf.headerListView reloadData];
                                     if (!weakSelf.headerListView.isClickButton) {
                                         [weakSelf.headerListView setNeedsDisplay];
                                     }
                                     
                                     if (index == weakSelf.currentIndex+1) {
                                         
                                         weakSelf.pageNum++;
                                         
                                         [weakSelf.dataArrays addObjectsFromArray:data];
                                         
                                         weakSelf.tableView.dataArrays = weakSelf.dataArrays;
                                         
                                         weakSelf.tableView.viewType = index;
                                         [weakSelf.tableView reloadData];
                                     }

                                     if (weakSelf.pageNum <= totlePageTemp) {

                                         [weakSelf.tableView.mj_footer endRefreshing];
                                     }
                                     else
                                     {
                                         if (weakSelf.dataArrays.count == 0) {

                                             [weakSelf.tableView setNullStringFooterText];
                                         }
                                         else {
                                             [weakSelf.tableView setNoMoreDataFooterText];
                                         }
                                         [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
                                     }
                                     
                                     if (weakSelf.dataArrays.count == 0) {
                                         [LZNoDataPublicView showNoDataViewInView:weakSelf.tableView];
                                     }
                                     else {
                                         [LZNoDataPublicView hiddenNoDataViewInView:weakSelf.tableView];
                                     }
                                     
                                 } resultFailed:^(NSString *error) {
                                     
                                     [weakSelf.tableView.mj_footer endRefreshing];
                                 }];

}

#pragma mark - HTHorizontalSelectionListDataSource Protocol Methods

- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList {
    return self.carMakes.count;
}

- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index {
    return self.carMakes[index];
}

#pragma mark - HTHorizontalSelectionListDelegate Protocol Methods

- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index {
    self.currentIndex = index;
    self.pageNum = 1;
    [self.dataArrays removeAllObjects];
    [self.tableView reloadData];
    [self.tableView.mj_footer beginRefreshing];
}

#pragma mark - Setter/Getter

- (LZMyCouponsTableView *)tableView {

    if (_tableView == nil) {
        _tableView = [[LZMyCouponsTableView alloc] initWithFrame:CGRectMake(0, 119, SCREEN_WIDTH, SCREEN_HEIGHT-119) style:UITableViewStyleGrouped];
        _tableView.viewType = 1;
    }
    
    return _tableView;
}

- (HTHorizontalSelectionList *)headerListView {

    if (_headerListView == nil) {
        _headerListView = [[HTHorizontalSelectionList alloc] init];
        [_headerListView setScrollViewColor:UIColorFromRGB(0xffffff, 1)];
        _headerListView.delegate = self;
        _headerListView.dataSource = self;
    }
    
    return _headerListView;
}
@end
